import { Repository , getRepository , FindManyOptions } from 'typeorm';
import { validate, ValidationError } from "class-validator";
import { NBAData } from '../entity/nba_data';
import { BaseContext } from 'koa';

export default class NBADataControl {
    public static async saveNBAData(nbaData: Array<NBAData>) {
        const nbaDataRepository: Repository<NBAData> = getRepository(NBAData);
        const errors: ValidationError[] = await validate(nbaData);
        if(errors.length > 0) console.log(errors);
        else await nbaDataRepository.save(nbaData);
    }
    public static async saveNBADataSingle(nbaData: NBAData) {
        const nbaDataRepository: Repository<NBAData> = getRepository(NBAData);
        const errors: ValidationError[] = await validate(nbaData);
        if(errors.length > 0) console.log(errors);
        else await nbaDataRepository.save(nbaData);
        try {
            if(errors.length > 0) console.log(errors);
            else await nbaDataRepository.save(nbaData);
        } catch (error) {
            console.log(error);
        }
    }

    public static async getNBADataLists(ctx: BaseContext) {
        try {
            const NBADataRepository: Repository<NBAData> = getRepository(NBAData);
            let { pageSize , pageIndex , dataType , playerId , teamId , season , seasonType } = ctx.request.body;
            pageIndex = pageIndex && pageIndex > 0 ? pageIndex-1 : 0;
            pageSize = pageSize || 10;
            let queryOptions: FindManyOptions<NBAData> = {
                relations: ["players","teams","rightAwayTeam","oppTeams","season","seasonType"],
                order: {
                    id: "DESC"
                },
                where: {},
                skip: pageIndex*pageSize,
                take: pageSize,
                cache: true,
            }
            let where = {};
            if(dataType && dataType !== '') Object.assign(where,{ dataType })
            if(playerId && playerId !== '') Object.assign(where,{ "players": playerId })
            if(teamId && teamId !== '') Object.assign(where,{ "teams": teamId })
            if(season && season !== '') Object.assign(where,{ "season": season })
            if(seasonType && seasonType !== '') Object.assign(where,{ "seasonType": seasonType })
            queryOptions.where = where;
            const [ nbaDataLists , total ] = await NBADataRepository.findAndCount(queryOptions);
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                nbaDataLists,
                total
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }
}